<?php

declare(strict_types=1);

namespace app\core;
use Swoole\Coroutine;
class Upload{
    public static function save(array $file){
       
        $destination='';
        try {
            $uploads_dir = './public/static/uploads/images';
            $tmp_name = $file["tmp_name"];
            $date=date('Ymd');
            $name = basename($file["name"]);
          
            preg_match('/\.[A-Z|a-z]{1,}$/',$name,$m);
            [$s1, $s2] = explode(' ', microtime());
            $filename=strval(sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000)).uniqid();
            $filename=uniqid($filename);
            $dir="$uploads_dir/$date";
            if(!file_exists($dir)){
                mkdir($dir);
            }

            $ext=$m[0];
            $destination="$dir/$filename$ext";
            $move_uploaded_file=move_uploaded_file($tmp_name,$destination);
            if(false===$move_uploaded_file){
                throw new \Exception("文件上传失败", 500);
                
            }
        } catch (\Throwable $th) {
            Log::error(['file' => $th->getFile(), 'line' => $th->getLine(), 'message' => $th->getMessage()]);
            return false;
        }
        return preg_replace('/^\.\//','',$destination);
    }
}
// $uploads_dir = '/uploads';
// foreach ($_FILES["pictures"]["error"] as $key => $error) {
//     if ($error == UPLOAD_ERR_OK) {
//         $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
//         // basename() may prevent filesystem traversal attacks;
//         // further validation/sanitation of the filename may be appropriate
//         $name = basename($_FILES["pictures"]["name"][$key]);
//         move_uploaded_file($tmp_name, "$uploads_dir/$name");
//     }
// }